package com.yoomiito.app.present.my.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.model.my.MyUserInfo;
import com.yoomiito.app.net.UploadFileManager;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.ui.my.MyUserInfoActivity;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.YMToast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;

public class MyUserInfoPresenter extends BaseActPresenter<MyUserInfoActivity> {


    private String mCurrentPhotoPath;

    public String getmCurrentPhotoPath() {
        return mCurrentPhotoPath;
    }

    public void setmCurrentPhotoPath(String mCurrentPhotoPath) {
        this.mCurrentPhotoPath = mCurrentPhotoPath;
    }

    public MyUserInfoPresenter(AppConfig appConfig) {
        super(appConfig);
    }

    public void getUserInfoData() {
        if (NetworkUtils.checkNetPermission(getV())){
            return;
        }
        YmApi.getYmService()
                .getMyUserInfo()
                .compose(getV().bindToLifecycle())
                .compose(XApi.<MyUserInfo>getApiTransformerData())
                .compose(XApi.<MyUserInfo>getScheduler())
                .subscribe(new ApiSubscriber<MyUserInfo>() {
                    @Override
                    public void onSuccess(MyUserInfo userInfo) {
                        getV().setUserInfo(userInfo);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        Toast.makeText(getV(), "error", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    public void setUserInfoData(String name, int sex, String birthday, String headimagurl) {
        if (NetworkUtils.checkNetPermission(getV())){
            return;
        }
        YmApi.getYmService().setMyUserInfo(name, sex == 0 ? "" : String.valueOf(sex), birthday, headimagurl)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<BaseModel>getApiTransformerNoData())
                .compose(XApi.<BaseModel>getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>() {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        YMToast.showText("修改成功");
                        getV().uploadSuccess();
                        getV().dismissLoading();
                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText(error.getMsg());
                        getV().dismissLoading();
                    }
                });
    }

    public void uploadPhotos(String name, int sex, String birthday,String path) {
        if (!TextUtils.isEmpty(path)) {
            UploadFileManager.uploadFile(path, "0", new UploadFileManager.UploadFileCallBack() {
                @Override
                public void uploadSucc(String filename, String key) {
                    Log.e("lin", "imageUrl-->" + filename);
                    setUserInfoData(name,sex,birthday,filename);
                }

                @Override
                public void uploadFail(int code, String key) {
                    YMToast.showText("上传失败");
                }
            });
        }
    }

    public void takeCamera(int num) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getV().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImageFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
//                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
//                        Uri.fromFile(photoFile));
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        getImageContentUri(photoFile));

            }
        }

        getV().startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
    }

    private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getV().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getV().getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
}
